"""
- 通过ip请求淘宝的一个接口获取到省份和运营商
- 接口：https://ip.taobao.com/outGetIpInfo?accessKey=alibaba-inc&ip=要查询的ip地址
- 每一行变成这种形式保存到文件
- 格式：ip,中国,湖南,电信
"""

import requests
import json
import pandas as pd
import os


def request1(ip: str) -> str:
    try:
        # 获取一个ip对应的信息
        respond = requests.get("https://ip.taobao.com/outGetIpInfo?accessKey=alibaba-inc&ip=" + ip)
        # 用json库转成字典格式
        respond1 = json.loads(respond.text)
        # 取data数据
        data = respond1["data"]
        # 调用写入csv的函数
        write_csv(data["ip"], data["country"], data["region"], data["isp"])
        return f'ip:{data["ip"]} 国家:{data["country"]} 省份:{data["region"]} 运营商:{data["isp"]}'
    except Exception as es:
        print("你输入的ip地址无效", es)
    return ''


def write_csv(ip: str, country: str, region: str, isp: str) -> None:
    # 判断csv文件是否为空来加表头
    if os.path.getsize("ip.csv"):
        # [[]]才是写到同一行, 而[]只是隔行写入
        dataframe = pd.DataFrame([[ip, country, region, isp]])
        # mode = "a",默认会覆盖文件，header要false不然有默认值
        dataframe.to_csv("ip.csv", mode="a", index=False, header=False, sep=',')
    else:
        dataframe = pd.DataFrame([[ip, country, region, isp]], columns=["ip", "country", "region", "isp"])
        dataframe.to_csv("ip.csv", mode="a", index=False, sep=',')


while True:
    ip1 = input("请输入需要查询的ip地址(按q退出）:")
    if ip1 == 'q':
        break
    print(request1(ip1))
